//
//  CYRegisterViewController.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/5.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYRegisterViewController.h"
#import "CYTextField.h"
#import "CYSecurityCell.h"
@interface CYRegisterViewController ()<UITextFieldDelegate,CYListTableViewDelegate>
@property (nonatomic, strong) CYTextField *userName;
@property (nonatomic, strong) CYTextField *passWord;
@property (nonatomic, strong) CYTextField *security;
@property (nonatomic, strong) CYTextField *answer;
@property (nonatomic, strong) CYImageView *readIMG;
@property (nonatomic, strong) CYButton *agreeMentBtn;
@property (nonatomic, strong) CYButton *registerBtn;
@property (nonatomic, strong) CYImageView *IMG;
@property (nonatomic, strong) CYView *line;
//下拉列表
@property (nonatomic, strong) CYListTableView *tableview;

@end

@implementation CYRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    /*注意顺序问题，tableview 要隐藏在输入用户名，输入密码，密保问题框之后，推出时，要显示在答案框之前*/
    self.answer.hidden = self.readIMG.hidden = self.agreeMentBtn.hidden = self.registerBtn.hidden = self.IMG.hidden =  self.tableview.hidden = self.userName.hidden = self.passWord.hidden = self.security.hidden  =  NO;
    self.line.hidden = NO;
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    // Do any additional setup after loading the view.
}

/*懒加载*/
- (CYTextField *)userName{
    if (!_userName) {
        _userName = [[CYTextField alloc]initWithLeftImage:@"user_login" Placeholder:@"请输入用户名"];
        _userName.autocapitalizationType = UITextAutocapitalizationTypeNone;//字母不自动大写
        _userName.detail_placeholder_size = AL(PT(22));
        _userName.detail_placeholder_color = RGBA(210, 210, 215, 1);
        _userName.detail_placeholder = @"(6-12位字母或数字)";
        _userName.keyboardType = UIKeyboardTypeASCIICapable;
        _userName.returnKeyType = UIReturnKeyNext;
        _userName.delegate = self;
        [self.view addSubview:_userName];
        
        [_userName mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).with.offset(AL(PT(60)));
            make.top.equalTo(self.view).with.offset(NAVIBAR_HEIGHT + STATUS_HEIGHT);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - AL(PT(60 * 2)), AL(PT(120))));
        }];
    }
    
    return _userName;
}

- (CYTextField *)passWord{
    if (!_passWord) {
        _passWord = [[CYTextField alloc]initWithLeftImage:@"lock" Placeholder:@"请输入密码"];
        _passWord.autocapitalizationType = UITextAutocapitalizationTypeNone;//字母不自动大写
        _passWord.keyboardType = UIKeyboardTypeASCIICapable;
        _passWord.detail_placeholder_size = AL(PT(22));
        _passWord.detail_placeholder_color = RGBA(210, 210, 215, 1);
        _passWord.detail_placeholder = @"(6-12位字母或数字组合)";
        _passWord.returnKeyType = UIReturnKeyNext;
        _passWord.secureTextEntry = YES;//密码暗文
        _passWord.delegate = self;
        [self.view addSubview:_passWord];
        
        [_passWord mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).with.offset(AL(PT(60)));
            make.top.equalTo(_userName.mas_bottom).with.offset(0);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - AL(PT(60 * 2)), AL(PT(120))));
        }];
    }
    
    return _passWord;
}
- (CYTextField *)security{
    if (!_security) {
        _security = [[CYTextField alloc]initWithLeftImage:@"problem" Placeholder:@"选择密保问题"];
        _security.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
        [_security setupRightview:@"xiala"];
        _security.delegate = self;
        [self.view addSubview:_security];
        
        [_security mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).with.offset(AL(PT(60)));
            make.top.equalTo(_passWord.mas_bottom).with.offset(0);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - AL(PT(60 * 2)), AL(PT(120))));
        }];
    }
    
    return _security;
}
- (CYTextField *)answer{
    if (!_answer) {
        _answer = [[CYTextField alloc]initWithPlaceholder:@"答:"];
        _answer.autocapitalizationType = UITextAutocapitalizationTypeNone;//字母不自动大写
        _answer.returnKeyType = UIReturnKeyDone;
        _answer.delegate = self;
        [self.view addSubview:_answer];
        
        [_answer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).with.offset(AL(PT(60)));
            make.top.equalTo(self.view).with.offset(AL(PT(120 *3)) + NAVIBAR_HEIGHT + STATUS_HEIGHT);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - AL(PT(60 * 2)), AL(PT(120))));
        }];
    }
    
    return _answer;
}
- (CYImageView *)readIMG{
    if (!_readIMG) {
        _readIMG = [[CYImageView alloc]initWithImage:[UIImage imageNamed:@"check"]];
        [self.view addSubview:_readIMG];
        
        [_readIMG mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_answer.mas_bottom).with.offset(AL(PT(80)));
            make.left.equalTo(self.view).with.offset(AL(PT(60 + 20)));
            make.size.mas_equalTo(CGSizeMake(AL(PT(16)), AL(PT(16))));
        }];
    }
    
    return _readIMG;
}

- (CYButton *)agreeMentBtn{
    if (!_agreeMentBtn) {
        _agreeMentBtn = [[CYButton alloc]initWithTitle:@"我已经满合法博彩年龄，且同意“开户协议”" titleColor:ColorHex(0x888888) backgroundColor:[UIColor whiteColor] cornerRadius:0.0];
        [_agreeMentBtn addTarget:self action:@selector(actionForAgreeMentBtn) forControlEvents:UIControlEventTouchUpInside];
        [_agreeMentBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        _agreeMentBtn.titleLabel.font = [UIFont systemFontOfSize:AL(PT(22))];
        [self.view addSubview:_agreeMentBtn];
        
        [_agreeMentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_readIMG);
            make.left.equalTo(_readIMG.mas_right).with.offset(AL(3));
            make.size.mas_equalTo([_agreeMentBtn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:AL(12)]}]);
        }];
    }
    return _agreeMentBtn;
}

- (CYButton *)registerBtn{
    
    if (!_registerBtn) {
        _registerBtn = [[CYButton alloc]initWithTitle:@"注册" titleColor:[UIColor lightGrayColor] backgroundColor:THEME_COLOR cornerRadius:5.0];
        [_registerBtn addTarget:self action:@selector(actionForRegisterBtn) forControlEvents:UIControlEventTouchUpInside];
        [_registerBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        _registerBtn.titleLabel.font = [UIFont systemFontOfSize:AL(PT(40))];
        [self.view addSubview:_registerBtn];
        
        [_registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_readIMG.mas_bottom).with.offset(AL(PT(26)));
            make.right.equalTo(self.view.mas_right).with.offset(-AL(PT(60)));
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - AL(PT(60 * 2)), AL(PT(80))));
        }];
    }
    
    return _registerBtn;
    
}

- (CYImageView *)IMG{
    if (!_IMG) {
        _IMG = [[CYImageView alloc]initWithImage:[UIImage imageNamed:@"background"]];
        [self.view addSubview:_IMG];
        
        [_IMG mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view.mas_bottom).with.offset(-AL(PT(60)));
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(AL(2 * PT(_IMG.image.size.width)), AL(2 * PT(_IMG.image.size.height))));
        }];
    }
    return _IMG;
}

- (CYView *)line{
    if (!_line) {
        _line = [[CYView alloc]initWithColor:[UIColor lightGrayColor]];
        [self.view addSubview:_line];
        
        [_line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(NAVIBAR_HEIGHT + STATUS_HEIGHT , 0, SCREEN_HEIGHT - NAVIBAR_HEIGHT - STATUS_HEIGHT - 0.5, 0));
        }];
    }
    
    return _line;
}

- (CYListTableView *)tableview{
    
    if (!_tableview) {
        _tableview = [[CYListTableView alloc]initWithArray:SECURITYQUESTION];
        _tableview.listTableDelegate = self;
        [self.view addSubview:_tableview];

        [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_answer.mas_top).with.offset(0);
            make.centerX.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - AL(PT(60 *2)), AL(44) * 5));
        }];
    }
    return _tableview;
}

//注册事件
- (void)actionForRegisterBtn{
    
    if (![self judgeTextLength]){
        [CYHUD show:@"请正确输入资料"];
        return;
    }
    
    NSString *string = [CYCache getIP];
    NSDictionary *dict = @{@"username":_userName.text,@"password":_passWord.text,@"question":_security.text,@"answer":_answer.text,@"reg_ip":string,@"click":@"yes"};
    
    //网络请求
    self.task = [CYHttps POST:API_register parameters:dict showHUD:YES progress:nil success:^(id data) {
        if (data) {//登录成功
            [CYHUD show:@"恭喜您，注册成功"];
            [CYUser shareUser].username = _userName.text;
            [CYUser shareUser].token = data;
            Class vc = NSClassFromString(@"CYTabBarController");
            UITabBarController *tabVC = (UITabBarController *)[vc new];
            tabVC.selectedIndex = 0;
            [[UIApplication sharedApplication] keyWindow].rootViewController = tabVC;
        }
    } failure:nil];
}

- (void)showList{
    
    [UIView animateWithDuration:0.3 animations:^{
        _tableview.transform = CGAffineTransformMakeTranslation(0, AL(44) *5);
    }];
    
}
- (void)actionForAgreeMentBtn{
    
}

- (void)actionForFreeTrial:(UIBarButtonItem *)sender{
    Class vc = NSClassFromString(@"CYFreeTrialViewController");
    [self.navigationController pushViewController:[vc new] animated:YES];
    
}

//监听键盘的高度,判断是否遮挡登陆按钮
- (void)keyboardWillShow:(NSNotification *)notification{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    CGFloat map = SCREEN_HEIGHT - CGRectGetMaxY(_registerBtn.frame) - height - 10;
    if (map < 0 && _answer.editing)
        [UIView animateWithDuration:0.3 animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, map);
            
        }];
    
}

//判定所有的textfiled的text是否为非空
- (BOOL)judgeTextLength{
    NSArray *array = [self.view subviews];
    BOOL isLength = YES;
    for (int i = 0; i < [array count]; i ++) {
        if ([array[i] isKindOfClass:[UITextField class]]) {
            UITextField *sub_textField = array[i];
            isLength = (sub_textField.text.length <= 0)?NO:isLength;
        }
    }
    return isLength;
}


- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - CYListTableViewDelegate - method
- (void)dataForSelectCell:(id)data indexPath:(NSIndexPath *)indexPath{
    _security.text = data;
}
#pragma mark uitextfield代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    BOOL length_bool =[self judgeTextLength];
    UIColor *color = (length_bool && (string.length > 0 || textField.text.length > 1))?[UIColor whiteColor]:[UIColor lightGrayColor];
    [_registerBtn setTitleColor:color forState:UIControlStateNormal];
    return YES;
}

//下拉选择
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    if ([textField.placeholder isEqualToString:@"选择密保问题"]) {
        [self showList];//弹出下拉选择表
        return NO;
    }
    return YES;
}

/*编辑时候，隐藏textfield的小文字*/
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    CYTextField *new_textfield = (CYTextField *)textField;
    [new_textfield hiddenDetailPlaceholderLBL:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
    return YES;
}


- (void)setupNavigationBarTintColor:(UIColor *)color{
    [super setupNavigationBarTintColor:[UIColor whiteColor]];
    self.navigationItem.title = @"用户注册";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"免费试玩" style:UIBarButtonItemStylePlain target:self action:@selector(actionForFreeTrial:)];
//    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}]; //设置导航栏标题 字体颜色
//    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]]; //设置导航栏背景颜色
//    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor blackColor]];  // 设置导航栏左按钮字体颜色
    [self.navigationItem.rightBarButtonItem setTintColor:THEME_COLOR];    //这是导航栏右按钮字体颜色
//    [self setStatusBarBackgroundColor:[UIColor whiteColor]];//状态栏背景颜色

    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
